    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Gebruiker;
import model.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Linda de Haan
 */
public class RegisterController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     * 
     */
    HttpSession sessie;
    MenuHandler menuHandler;
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        SessionFactory sessionFactory=SchoolContentManager.sessionFactory;
        Session session = sessionFactory.getCurrentSession(); //get the session from the sessionFactory
        Transaction transaction = session.beginTransaction(); //start the transaction
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        sessie = request.getSession();
        menuHandler=new MenuHandler(sessie);
        Gebruiker user = new Gebruiker();
        Student student = new Student();

        if (!request.getParameter("email").isEmpty() && !request.getParameter("firstname").isEmpty()
                && !request.getParameter("lastname").isEmpty() && !request.getParameter("bankaccount").isEmpty() &&
                !request.getParameter("password1").isEmpty()
                && !request.getParameter("password2").isEmpty()) { //check if everything is filled in
            System.out.println("alles is ingevuld ----------------------------------------!");
            if (!request.getParameter("password1").equals(request.getParameter("password2"))) { //check if the two inserted password are equal
                System.out.println("de wachtwoorden matchen niet met elkaar ------------------!");
                sessie.setAttribute("registreerfout", "<b>The two entered passwords has to be the same!</b>");
                sessie.setAttribute("contentPage", "/register.jsp");
            } else if(!checkmail(request.getParameter("email"))){
                sessie.setAttribute("registreerfout", "<b>You enterd an invalid email!</b>");
                sessie.setAttribute("contentPage", "/register.jsp");
            }else{
                String getUserSQL = "SELECT * FROM gebruiker g WHERE g.email = '" + request.getParameter("email") + "'";
                ArrayList<Gebruiker> users = (ArrayList) session.createSQLQuery(getUserSQL).list(); //Get all information from user by using email and password

                Iterator it = users.iterator();
                if (!it.hasNext()) {

                    System.out.println("gebruiker is toegevoegd ----------------------------!");
                    student.setEmail(request.getParameter("email").toLowerCase()); //set the values of the user to given values
                    student.setFirstName(request.getParameter("firstname"));
                    student.setInsertion(request.getParameter("insertion"));
                    student.setLastName(request.getParameter("lastname"));
                    student.setPassword(request.getParameter("password1"));
                    student.setBankaccountnr(request.getParameter("bankaccount"));
                    user=student.getUser();
                    //session.save(user);
                    session.save(student);
                    transaction.commit(); //commit user to data
//                    sessie.setAttribute("user", user.getuCode());
//                sessie.setAttribute("cuser", user);
//                
//                menuHandler = new MenuHandler(sessie);
//
//                menuHandler.menuAdd("selectCourse", "Course Catalogue");
//                menuHandler.menuAdd("logout","Logout");
//                
//                setTypeuser();
                    sessie.setAttribute("contentPage", "login.jsp");
//                    
//                    sessie.setAttribute("userStuffPage", "empty.jsp");
                    new MailController().mail("Thank you for making a account at Three2Learn!", "acount created at three2learn", (String)request.getParameter("email"));
        
                } else {
                    sessie.setAttribute("registreerfout", "<b>Email already in use!</b>");

                    sessie.setAttribute("contentPage", "/register.jsp");

                }
            }
        } else {
            System.out.println("niet alles is ingevuld --------------------------------- !");
            sessie.setAttribute("registreerfout", "<b>Everything has to be filled in!</b>");
            sessie.setAttribute("contentPage", "/register.jsp");
        }

        response.sendRedirect("index");
    }
    public boolean checkmail(String email){
        //Set the email pattern string
      Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

      //Match the given string with the pattern
      Matcher m = p.matcher(email);

      //check whether match is found 
      boolean matchFound = m.matches();

      if (matchFound){
        //System.out.println("Valid Email Id.");
      
          return true;
      }else{
        //System.out.println("Invalid Email Id.");
        
          return false;
   }
      
    }
    private void setTypeuser() {
        
        Session session = SchoolContentManager.getSessionFactory().getCurrentSession(); //get the session from the sessionFactory
        
        Transaction transaction = session.beginTransaction();
        String gebruikerCode=(String)sessie.getAttribute("user");
        String getUserSQL = "SELECT * FROM teacher t WHERE t.uCode='"+gebruikerCode+"'";
            ArrayList<Object[]> users = (ArrayList) session.createSQLQuery(getUserSQL).list(); //Get all information from user by using email and password

            Iterator it = users.iterator();
            sessie.setAttribute("isAdmin", false);
            if (it.hasNext()) {
                Object[] row = (Object[]) it.next();
                if(row[0].equals(true)){
                    sessie.setAttribute("isAdmin", true);
                    System.out.println("blablabla\t\tblablabla");
                    menuHandler.addAdminOptions();
                    
                }
                sessie.setAttribute("isTeacher", true);
            } else {
                sessie.setAttribute("isTeacher", false);
            }
            transaction.commit();
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}